package my.chat.controller;

import my.chat.entity.Login;
import my.chat.service.LoginService;
import my.chat.util.MD5Utils;
import my.chat.util.exception.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/")
    public String toLogin(){
        return "user/login";
    }

    /**
     * 登陆
     * */
    @PostMapping("/justLogin")
    @ResponseBody
    public R login(@RequestBody Login login, HttpSession session) {
        login.setPassword(MD5Utils.getMD5Str(login.getPassword()));
        String userId = loginService.justLogin(login);
        if (StringUtils.isEmpty(userId)) {
            return R.error().message("账号或者密码错误");
        }
        session.setAttribute("userId", userId);
        return R.ok().message("登录成功");
    }
}
